package com.atguigu.gmall.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.PropertyNamingStrategy;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.atguigu.gmall.realtime.app.BaseApp;
import com.atguigu.gmall.realtime.bean.TradeSkuOrderBean;
import com.atguigu.gmall.realtime.commont.Constant;
import com.atguigu.gmall.realtime.function.AsyncDimFunctionHBase;
import com.atguigu.gmall.realtime.util.AtguiguUtil;
import com.atguigu.gmall.realtime.util.DateFormatUtil;
import com.atguigu.gmall.realtime.util.DorisUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.AsyncDataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.math.BigDecimal;
import java.time.Duration;
import java.util.concurrent.TimeUnit;

/**
 * @Author lzc
 * @Date 2023/5/4 09:33
 */
public class Dws_09_DwsTradeSkuOrderWindow_Cache_Async_Doris extends BaseApp {
    public static void main(String[] args) {
        new Dws_09_DwsTradeSkuOrderWindow_Cache_Async_Doris().init(
            40009,
            2,
            "Dws_09_DwsTradeSkuOrderWindow_Cache_Async",
            Constant.TOPIC_DWD_TRADE_ORDER_DETAIL
        );
    }
    
    @Override
    public void handle(StreamExecutionEnvironment env, DataStreamSource<String> stream) {
        // 1. 解析到pojo 中
        SingleOutputStreamOperator<TradeSkuOrderBean> beanStream = parseToPojo(stream);
        // 2. 按照订单详情 id 去重
        SingleOutputStreamOperator<TradeSkuOrderBean> distinctedBeanStream = distinctByOrderDetailId(beanStream);
        // 3. 开窗聚合
        SingleOutputStreamOperator<TradeSkuOrderBean> streamWithoutDims = windowAndAgg(distinctedBeanStream);
        // 4. 补充维度
        SingleOutputStreamOperator<TradeSkuOrderBean> streamWitDims = joinDims(streamWithoutDims);
        streamWitDims.print();
        // 5. 写出到到 clickhouse
        writeToClickHouse(streamWitDims);
        
    }
    
    private void writeToClickHouse(SingleOutputStreamOperator<TradeSkuOrderBean> streamWitDims) {
        //        streamWitDims.addSink(FlinkSinkUtil.getClickHouseSink("dws_trade_sku_order_window", TradeSkuOrderBean.class));
        streamWitDims
            .map(bean -> {
                SerializeConfig config = new SerializeConfig();
                config.propertyNamingStrategy = PropertyNamingStrategy.SnakeCase;  // 转成json的时候, 属性名使用下划线
                return JSON.toJSONString(bean, config);
            })
            .sinkTo(DorisUtil.getDorisSink("gmall.dws_trade_sku_order_window"));
    }
    
    private SingleOutputStreamOperator<TradeSkuOrderBean> joinDims(
        SingleOutputStreamOperator<TradeSkuOrderBean> stream) {
        
        SingleOutputStreamOperator<TradeSkuOrderBean> skuInfoStream = AsyncDataStream.unorderedWait(
            stream,
            new AsyncDimFunctionHBase<TradeSkuOrderBean>() {
                
                @Override
                public String getTable() {
                    return "dim_sku_info";
                }
                
                @Override
                public String getId(TradeSkuOrderBean bean) {
                    return bean.getSkuId();
                }
                
                @Override
                public void addDim(TradeSkuOrderBean bean,
                                   JSONObject dim) {
                    bean.setSkuName(dim.getString("sku_name"));
                    bean.setSpuId(dim.getString("spu_id"));
                    bean.setTrademarkId(dim.getString("tm_id"));
                    bean.setCategory3Id(dim.getString("category3_id"));
                }
            },
            60,
            TimeUnit.SECONDS
        );
        
        SingleOutputStreamOperator<TradeSkuOrderBean> spuInfoStream = AsyncDataStream.unorderedWait(
            skuInfoStream,
            new AsyncDimFunctionHBase<TradeSkuOrderBean>() {
                @Override
                public String getTable() {
                    return "dim_spu_info";
                }
                
                @Override
                public String getId(TradeSkuOrderBean bean) {
                    return bean.getSpuId();
                }
                
                @Override
                public void addDim(TradeSkuOrderBean bean,
                                   JSONObject dim) {
                    bean.setSpuName(dim.getString("spu_name"));
                }
            },
            60,
            TimeUnit.SECONDS
        );
        
        SingleOutputStreamOperator<TradeSkuOrderBean> tmStream = AsyncDataStream.unorderedWait(
            spuInfoStream,
            new AsyncDimFunctionHBase<TradeSkuOrderBean>() {
                @Override
                public String getTable() {
                    return "dim_base_trademark";
                }
                
                @Override
                public String getId(TradeSkuOrderBean bean) {
                    return bean.getTrademarkId();
                }
                
                @Override
                public void addDim(TradeSkuOrderBean bean,
                                   JSONObject dim) {
                    bean.setTrademarkName(dim.getString("tm_name"));
                }
            },
            60,
            TimeUnit.SECONDS
        );
        
        SingleOutputStreamOperator<TradeSkuOrderBean> c3Stream = AsyncDataStream.unorderedWait(
            tmStream,
            new AsyncDimFunctionHBase<TradeSkuOrderBean>() {
                @Override
                public String getTable() {
                    return "dim_base_category3";
                }
                
                @Override
                public String getId(TradeSkuOrderBean bean) {
                    return bean.getCategory3Id();
                }
                
                @Override
                public void addDim(TradeSkuOrderBean bean,
                                   JSONObject dim) {
                    bean.setCategory3Name(dim.getString("name"));
                    bean.setCategory2Id(dim.getString("category2_id"));
                }
            },
            60,
            TimeUnit.SECONDS
        );
        
        SingleOutputStreamOperator<TradeSkuOrderBean> c2Stream = AsyncDataStream.unorderedWait(
            c3Stream,
            new AsyncDimFunctionHBase<TradeSkuOrderBean>() {
                @Override
                public String getTable() {
                    return "dim_base_category2";
                }
                
                @Override
                public String getId(TradeSkuOrderBean bean) {
                    return bean.getCategory2Id();
                }
                
                @Override
                public void addDim(TradeSkuOrderBean bean,
                                   JSONObject dim) {
                    bean.setCategory2Name(dim.getString("name"));
                    bean.setCategory1Id(dim.getString("category1_id"));
                }
            },
            60,
            TimeUnit.SECONDS
        );
        
        return AsyncDataStream.unorderedWait(
            c2Stream,
            new AsyncDimFunctionHBase<TradeSkuOrderBean>() {
                @Override
                public String getTable() {
                    return "dim_base_category1";
                }
                
                @Override
                public String getId(TradeSkuOrderBean bean) {
                    return bean.getCategory1Id();
                }
                
                @Override
                public void addDim(TradeSkuOrderBean bean,
                                   JSONObject dim) {
                    bean.setCategory1Name(dim.getString("name"));
                }
            },
            60,
            TimeUnit.SECONDS
        );
        
    }
    
    private SingleOutputStreamOperator<TradeSkuOrderBean> windowAndAgg(
        SingleOutputStreamOperator<TradeSkuOrderBean> stream) {
        return stream
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<TradeSkuOrderBean>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((bean, ts) -> bean.getTs())
                    .withIdleness(Duration.ofSeconds(60))
            
            )
            .keyBy(TradeSkuOrderBean::getSkuId)
            .window(TumblingEventTimeWindows.of(Time.seconds(5)))
            .reduce(
                new ReduceFunction<TradeSkuOrderBean>() {
                    @Override
                    public TradeSkuOrderBean reduce(TradeSkuOrderBean value1,
                                                    TradeSkuOrderBean value2) throws Exception {
                        value1.setOrderAmount(value1.getOrderAmount().add(value2.getOrderAmount()));
                        value1.setOriginalAmount(value1.getOriginalAmount().add(value2.getOriginalAmount()));
                        value1.setActivityAmount(value1.getActivityAmount().add(value2.getActivityAmount()));
                        value1.setCouponAmount(value1.getCouponAmount().add(value2.getCouponAmount()));
                        return value1;
                    }
                },
                new ProcessWindowFunction<TradeSkuOrderBean, TradeSkuOrderBean, String, TimeWindow>() {
                    @Override
                    public void process(String skuId,
                                        Context ctx,
                                        Iterable<TradeSkuOrderBean> elements,
                                        Collector<TradeSkuOrderBean> out) throws Exception {
                        TradeSkuOrderBean bean = elements.iterator().next();
                        bean.setStt(AtguiguUtil.tsToDateTime(ctx.window().getStart()));
                        bean.setEdt(AtguiguUtil.tsToDateTime(ctx.window().getEnd()));
                        bean.setCurDate(DateFormatUtil.toPartitionDate(ctx.window().getStart()));
                        
                        bean.setTs(System.currentTimeMillis());  //
                        out.collect(bean);
                    }
                }
            );
        
    }
    
    private SingleOutputStreamOperator<TradeSkuOrderBean> distinctByOrderDetailId(
        SingleOutputStreamOperator<TradeSkuOrderBean> beanStream) {
        return beanStream
            .keyBy(TradeSkuOrderBean::getOrderDetailId)
            .process(new KeyedProcessFunction<String, TradeSkuOrderBean, TradeSkuOrderBean>() {
                
                private ValueState<TradeSkuOrderBean> lastBeanState;
                
                @Override
                public void open(Configuration parameters) throws Exception {
                    lastBeanState = getRuntimeContext().getState(new ValueStateDescriptor<TradeSkuOrderBean>("lastBean", TradeSkuOrderBean.class));
                }
                
                @Override
                public void processElement(TradeSkuOrderBean currentBean,
                                           Context ctx,
                                           Collector<TradeSkuOrderBean> out) throws Exception {
                    TradeSkuOrderBean lastBean = lastBeanState.value();
                    // 当第一条来了,直接输出
                    if (lastBean == null) {
                        out.collect(currentBean);
                    } else {
                        // 不是第一条, 应该用当前数据 - 上一条的数据
                        // 把减完后的数据存入到 lastBean, 然后输出
                        lastBean.setOriginalAmount(currentBean.getOriginalAmount().subtract(lastBean.getOriginalAmount()));
                        lastBean.setActivityAmount(currentBean.getActivityAmount().subtract(lastBean.getActivityAmount()));
                        lastBean.setCouponAmount(currentBean.getCouponAmount().subtract(lastBean.getCouponAmount()));
                        lastBean.setOrderAmount(currentBean.getOrderAmount().subtract(lastBean.getOrderAmount()));
                        out.collect(lastBean);
                    }
                    
                    // 当数据总是会放入到状态, 供下一条使用
                    lastBeanState.update(currentBean);
                }
            });
    }
    
    private SingleOutputStreamOperator<TradeSkuOrderBean> parseToPojo(DataStreamSource<String> stream) {
        return stream
            .map(new MapFunction<String, TradeSkuOrderBean>() {
                @Override
                public TradeSkuOrderBean map(String value) throws Exception {
                    JSONObject obj = JSON.parseObject(value);
                    return TradeSkuOrderBean.builder()
                        .skuId(obj.getString("sku_id"))
                        .originalAmount(obj.getBigDecimal("split_original_amount"))
                        .activityAmount(obj.getBigDecimal("split_activity_amount") == null ? new BigDecimal("0.0") : obj.getBigDecimal("split_activity_amount"))
                        .couponAmount(obj.getBigDecimal("split_coupon_amount") == null ? new BigDecimal("0.0") : obj.getBigDecimal("split_coupon_amount"))
                        .orderAmount(obj.getBigDecimal("split_total_amount"))
                        .ts(obj.getLong("ts") * 1000)
                        .orderDetailId(obj.getString("id"))
                        .build();
                }
            });
    }
}
/*
默认情况下, 算子对数据的处理都是同步方式: 上一个元素没有处理完, 不会开始处理下一个元素

1. 增加并行度
    有限制, 资源的利用.
    
2. 异步的方式处理元素

----
不阻塞

连接数据库的时候,需要异步客户端配合
    目前我用的 redis 的客户端和 phoenix 的客户端不支持异步连接
    
多线程+多客户端(同步客户端)
    如果要异步处理多个元素,就启动多个线程,每个线程内创建一个客户端,这个客户端只处理一个元素
 

 */